package me.xiaoyan.ehr.config;

import me.xiaoyan.ehr.vo.ApiResponseData;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;

/**
 * 统一处理异常
 */
@RestControllerAdvice
public class AppExceptionHandler {
    @ExceptionHandler(SQLException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public ApiResponseData<String> sqlExceptionHandler(HttpServletRequest req, SQLException e) {
        ApiResponseData<String> error = new ApiResponseData<>();
        error.setCode(-1);
        error.setMessage("数据库执行异常:" + e.getMessage());
        return error;
    }

    //
    @ExceptionHandler(value = Exception.class) // 要捕获的异常类型
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public ApiResponseData<String> exceptionHandler(HttpServletRequest req, Exception e) {
        ApiResponseData<String> error = new ApiResponseData<>();
        error.setCode(-1);
        error.setMessage("App Internal Error:" + e.getMessage());
        return error;
    }
}
